import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router/index.js'
import moment from 'dayjs'

//根据类型对数组进行分组；
//比如根据id进行分类分割成[[{id:1,key:1},{id:1,key:2},[{id:2,key:1},{id:2,Key:2}]]
const groupBy = function (list, name) {

  return list.reduce((obj, item) => {
    if (!obj[item[name]]) {
      obj[item[name]] = []
      obj[item[name]].push(item)
    } else {
      obj[item[name]].push(item)
    }
    return obj
  }, {})
}
export default {
  // 处理树形数据 children没数据时处理为null
  filterChildren: function (data) {
    data.forEach(item => {
      if (!item.children) return data
      if (item.children && !item.children.length) {
        item.children = null
        return data
      }
      this.filterChildren(item.children)
    })
    return data
  },
  uploadValidImage: function (file) {
    let fileTypes = ['jpg', 'jpeg', 'png', 'gif']
    let fileName = file.name.toLowerCase()
    let fileType = fileName.slice(
      fileName.lastIndexOf('.') + 1,
      fileName.length
    )
    // 上传的文件不符合fileTypes
    if (fileTypes.indexOf(fileType) == -1) {
      return false
    } else {
      return true
    }
  },
  uploadValidExcel: function (file) {
    let fileTypes = ['xlsx', 'xls']
    let fileName = file.name.toLowerCase()
    let fileType = fileName.slice(
      fileName.lastIndexOf('.') + 1,
      fileName.length
    )
    // 上传的文件不符合fileTypes
    if (fileTypes.indexOf(fileType) == -1) {
      return false
    } else {
      return true
    }
  },
  toThousands: function (value) {
    if (value == 0) return '0'
    if (!value) return
    let result = value.toString().replace(/\d+/, function (n) {
      return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
        return $1 + ','
      })
    })
    return result
  },
  messageError: function (msg) {
    Message({
      showClose: true,
      message: msg,
      duration: 100000,
      type: 'error'
    })
  },
  messageError2000: function (msg) {
    Message({
      showClose: true,
      message: msg,
      duration: 20000,
      type: 'error'
    })
  },
  downloadFile: function (url, fileName, params = {}, fileTypes = 'xls') {
    if (params && params.totals) {
      delete params.totals
      delete params.totalPages
    }
    for (var key in params) {
      if (!params[key]) {
        delete params[key]
      }
    }
    return axios
      .post(url, params, {
        responseType: 'blob'
      })
      .then(res => {
        if (!res) return
        let url = window.URL.createObjectURL(res.data)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        //文件名加上当前时间
        let time = moment(new Date().getTime()).format('YYYYMMDDHHmmss')
        //如果请求头里返回文件名，则直接使用请求头的文件名；若没，则使用页面中设置的
        link.setAttribute('download', `${fileName}_${time}.${fileTypes}`)
        document.body.appendChild(link)
        link.click()
      })
      .catch(err => {
        this.$message.error(err);
      })
  },
  downloadFileSync: function (url, params = {}, checkParams = {}) {
    for (var key in checkParams) {
      if (!checkParams[key]) {
        Message.error(`请选择111`)
        return
      }
    }
    for (var key1 in params) {
      if (!params[key1]) {
        delete params[key1]
      }
    }
    return axios
      .get(url, {
        params: {
          ...params
        }
      })
      .then(res => {
        if (res.data.Status == 'true') {
          let info = '正在导出，请到上传下载--下载结果页面查看导出结果'
          let message = Message({
            type: 'success',
            showClose: true,
            duration: 5000,
            dangerouslyUseHTMLString: true,
            message: `<span>${info}</span>`
          })

          message.$el.querySelector('span').onclick = () => {
            router.push('/downResult')
          }
        }
      })
  },
  // 刷新时清除表格排序样式
  clearTableSortStyle (table) {
    table.columns.forEach(item => {
      if (item.order) item.order = ''
    })
    table.clearSort()
  },
  dealParameter (params) {
    for (var key in params) {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key]
      }
    }
    return params
  },
  compare (property) {
    return function (a, b) {
      var value1 = a[property]
      var value2 = b[property]
      return value1 - value2
    }
  },
  // 返回上一个路由
  backTopHistory () {
    router.go(-1);
  },
  groupByData: groupBy,
  /**
   * 让数组分页处理打印
   * @param {list} 数组 
   * @param {*pageSize} 一页打印几个订单 
   * @param {*name} 根据物流分别打印 
   */
  getArrPagePrint: function (datalist, pageSize, name) {
    let list = groupBy(datalist, name);
    let newResultArray = []
    for (let current in list) {
      current = list[current]
      if (current instanceof Array && current.length > 0) {
        let total = Math.ceil(current.length / pageSize);
        let i = 0
        while (current.length > 0) {
          i++
          let temp0ARRay = current.splice(0, pageSize)
          newResultArray.push({
            pageIndex: i,
            total,
            data: temp0ARRay
          })
        }

      }
    }
    return newResultArray;
  },
  // 打印所有的数据
  printAllData: function (datalist) {
    let newResultArray = [];
    newResultArray.push({
      pageIndex: 1,
      total: 1,
      data: datalist
    })
    return newResultArray;
  },
}
